package com.su83.printerdroid;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import com.android.future.usb.UsbManager;

import com.su83.printerdroid.Printcore;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements Runnable {
	private static final String ACTION_USB_PERMISSION = "com.google.android.DemoKit.action.USB_PERMISSION";
	private static final String TAG = "PrinterDroid";
	private UsbManager mUsbManager;

	Button btnDebugSend;
	TextView textView1;

	com.android.future.usb.UsbAccessory mAccessory;
	ParcelFileDescriptor mFileDescriptor;
	FileInputStream mInputStream;
	FileOutputStream mOutputStream;

	Printcore printcore;

	private PendingIntent mPermissionIntent;
	private boolean mPermissionRequestPending;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		textView1 = (TextView) findViewById(R.id.textView1);
		
		btnDebugSend = (Button) findViewById(R.id.button1);
		btnDebugSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				sendCommand("M105\n");
			}
		});

		linkAndOpenUsbAccessory();
		textView1.append("Linked USB\n");
		printcore = new Printcore();
	}

	/**
	 * 
	 */
	private void linkAndOpenUsbAccessory() {
		mUsbManager = UsbManager.getInstance(this);
		mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
				ACTION_USB_PERMISSION), 0);
		IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
		filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
		registerReceiver(mUsbReceiver, filter);

		if (getLastNonConfigurationInstance() != null) {
			mAccessory = (com.android.future.usb.UsbAccessory) getLastNonConfigurationInstance();
			openAccessory(mAccessory);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private void openAccessory(com.android.future.usb.UsbAccessory mAccessory2) {
		mFileDescriptor = mUsbManager.openAccessory(mAccessory2);
		if (mFileDescriptor != null) {
			mAccessory = mAccessory2;
			FileDescriptor fd = mFileDescriptor.getFileDescriptor();
			mInputStream = new FileInputStream(fd);
			mOutputStream = new FileOutputStream(fd);
			Thread thread = new Thread(null, this, "PrintDroid");
			thread.start();
			textView1.append("Thread started\n");
			Log.d(TAG, "accessory opened");
			enableControls(true);
		} else {
			Log.d(TAG, "accessory open fail");
		}
	}

	public void run() {
        int ret = 0;
        byte[] buffer = new byte[16384];
        int i;

        while (ret >= 0) {
                try {
                        ret = mInputStream.read(buffer);
                } catch (IOException e) {
                        break;
                }       // try/catch

                i = 0;
                while (i < ret) {
                        int len = ret - i;

                        switch (buffer[i]) {
                        default:
                        	
                                Log.d(TAG, "unknown msg: " + buffer[i]);
                                i = len;
                                break;
                        }       // switch
                }       // while 2

        }       // while 1
}       // run()       



	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
			//if(msg.="ERROR:") { 
		//		StatusMsg o = (StatusMsg) msg.obj;
			//	handleSwitchMessage(o);
			//	break;
		//	}
		}
	};

	
	 //Write String to Adk
	public void sendCommand(String text){
	  Toast.makeText(getBaseContext(), "Sending", Toast.LENGTH_SHORT).show();
	  byte[] buffer = text.getBytes();
	 
	  if(mOutputStream != null){
	    
	   try {
		   mOutputStream.write(buffer);
	   } catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	   } 
	  }
	 }

	protected void enableControls(boolean enable) {
	}

	private void closeAccessory() {
		enableControls(false);

		try {
			if (mFileDescriptor != null) {
				mFileDescriptor.close();
			}
		} catch (IOException e) {
		} finally {
			mFileDescriptor = null;
			mAccessory = null;
		}
	}

	@Override
	public void onResume() {
		super.onResume();

		@SuppressWarnings("unused")
		Intent intent = getIntent();
		if (mInputStream != null && mOutputStream != null) {
			return;
		}

		com.android.future.usb.UsbAccessory[] accessories = mUsbManager
				.getAccessoryList();
		com.android.future.usb.UsbAccessory accessory = (accessories == null ? null
				: accessories[0]);
		if (accessory != null) {
			if (mUsbManager.hasPermission(accessory)) {
				openAccessory(accessory);
			} else {
				synchronized (mUsbReceiver) {
					if (!mPermissionRequestPending) {
						mUsbManager.requestPermission(accessory,
								mPermissionIntent);
						mPermissionRequestPending = true;
					}
				}
			}
		} else {
			Log.d(TAG, "mAccessory is null");
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		closeAccessory();
	}

	@Override
	public void onDestroy() {
		unregisterReceiver(mUsbReceiver);
		super.onDestroy();
	}

	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_USB_PERMISSION.equals(action)) {
				synchronized (this) {
					com.android.future.usb.UsbAccessory accessory = UsbManager
							.getAccessory(intent);
					if (intent.getBooleanExtra(
							UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
						openAccessory(accessory);
					} else {
						Log.d(TAG, "permission denied for accessory "
								+ accessory);
					}
					mPermissionRequestPending = false;
				}
			} else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
				com.android.future.usb.UsbAccessory accessory = UsbManager
						.getAccessory(intent);
				if (accessory != null && accessory.equals(mAccessory)) {
					closeAccessory();
				}
			}
		}
	};

	protected class StatusMsg {
		private byte Status[];
		private String state;

		public StatusMsg(byte aStatus[]) {
			this.Status = aStatus;
			this.state = aStatus.toString();
		}

		public byte[] getStatus() {
			return Status;
		}

		public void setStatus(byte[] status) {
			Status = status;
		}

		public String getState() {
			return state;
		}

		public void setState(String state) {
			this.state = state;
		}


	}
}

